<template>
	<view>
		<view style="display: inline;" v-if="!isSessionKey">
			<button v-if="!isphonenumber || !toggle" :class="classname" open-type="getPhoneNumber"  @getphonenumber="handleGetPhoneNumber">{{btntxt}}</button>
			<slot v-else></slot>
		</view>
		<slot v-else></slot>
	</view>
</template>
<script>
	import cache from '@/config/cache'
	import userService from '@/service/user/UserService'
	import loginService from '@/service/login/LoginService'	
	export default {
		name:"pug-userinfo",
		props:{
			classname:{
				type:String,
				default:"",
			},
			btntxt:{
				type:String,
				default:"",
			},
			toggle:{
				type:Boolean,
				default:false,
			}
		},
		
		data() {
			return {
				isphonenumber:false,
				isSessionKey:false
			};
		},
		
		created(){
			this.isSessionKey = getApp().isEmpty(getApp().getUser().sessionkey);
			this.isphonenumber = cache.get("isphonenumber") || false;
		},
		
		methods:{
			async handleGetPhoneNumber(e){
				// 1: 修改状态
				this.isphonenumber = true;
				this.toggle = true;
				// 2: 全局缓存开关控制手机是否授权
				cache.set("isphonenumber",true);
				this.$emit("toggle",true);
				try{
					// 3：获取微信手机授权的加密信息 
					var {
						code,iv,encryptedData:encrypted
					} = e.detail;
					// 4: 拿到微信登录的sessionkey
					var sessionkey = getApp().getUser().sessionkey;
					// 5:为什么这里userid不到服务器端获取，因为登录没有/api开头不会拦截所有在服务端是获取不到用户信息的
					var userid = getApp().getUser().id;
					// 6：把手机的加密信息和sessionkey发起异步请求去服务端进行解析
					var res = await loginService.weixinPhone({userid,code,iv,sessionkey,encrypted});
					if(res.data){
						// 获取缓存用户信息进行替换
						var cacheUserInfo = getApp().getUser();
						cacheUserInfo.phone = res.data.phonenumber;
						// 同步缓存 	
						getApp().setUser(cacheUserInfo);
						uni.$u.toast("授权成功!");
					}
				}catch(e){
					
				}
			}
		}
	}
</script>

<style>
	.pug-button-phonenumer{position: absolute;top:0;left:0;right:0;bottom:0;background:red;z-index: 10000;}
</style>
